//
//  NewsDetailViewController.swift
//  OSCChina
//
//  Created by 刘威 on 2016/11/30.
//  Copyright © 2016年 刘威. All rights reserved.
//

import UIKit
import Alamofire
import WebKit
import MBProgressHUD
import YYCache

class NewsDetailViewController: UIViewController,WKNavigationDelegate {

    var blogId = ""
    var newsType:NewsType = NewsType.Blog
    var webView = WKWebView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.title = "资讯"
        self.view.backgroundColor = UIColor.white
        self.navigationController?.navigationBar.tintColor = UIColor.white
        // Do any additional setup after loading the view.
        print("news type:\(newsType)")
        var news_detail_api = "https://www.oschina.net/action/apiv2/blog?id=\(self.blogId)"
        if newsType == NewsType.Info{
            news_detail_api = "https://www.oschina.net/action/apiv2/news?id=\(self.blogId)"
        }
        //创建wkwebview
        self.webView = WKWebView(frame: self.view.frame)
        self.webView.backgroundColor = UIColor.clear
        //self.webView.navigationDelegate = self
        //添加wkwebview
        self.view.addSubview(self.webView)
        
        getNewsDetail(news_detail_api)
    }
    
    
    func getNewsDetail(_ url:String){
        
        let hud = MBProgressHUD.showAdded(to: self.view, animated: true)

        let cache = YYCache(name: "newsCache")
        cache?.memoryCache.shouldRemoveAllObjectsOnMemoryWarning = true
        cache?.memoryCache.shouldRemoveAllObjectsWhenEnteringBackground = true
        let object = cache!.object(forKey: url)
        
        Alamofire.request(url).responseJSON { response in
            switch response.result{
            case.success(let json):
                
                cache?.setObject(json as? NSCoding, forKey: url)
                let dict = json as! Dictionary<String,AnyObject>
                if dict["result"] != nil{
                    
                    let body = dict["result"]!["body"]
                    let author = dict["result"]!["author"]
                    let title = dict["result"]!["title"]
                    let pubDate = dict["result"]!["pubDate"] as! String
                    
                    let dateString = pubDate.components(separatedBy: " ")[0]
                    
                    let data = ["content":body,"author":author,
                                "title":title,"pubDate":dateString]
                    
                    let htmlString =  Utils.HTMLRenderWithData(data:data as AnyObject,templateName:"article")
                    self.webView.loadHTMLString(htmlString, baseURL: Bundle.main.bundleURL)
                }//else{
                    hud.hide(animated: true)
                //}
            case.failure(let error):
                
                if (object != nil) {
                    let dict = object as! Dictionary<String,AnyObject>
                    if dict["result"] != nil{
                        
                        let body = dict["result"]!["body"];
                        let author = dict["result"]!["author"];
                        let title = dict["result"]!["title"];
                        
                        let data = ["content":body,"author":author,"title":title]
                        
                        let htmlString =  Utils.HTMLRenderWithData(data:data as AnyObject,templateName:"article")
                        self.webView.loadHTMLString(htmlString, baseURL: Bundle.main.bundleURL)
                    }
                }else{
                    hud.mode = MBProgressHUDMode.text
                    hud.label.text = error.localizedDescription;
                    hud.hide(animated: true, afterDelay: 3.0)
                }
            }
        }
    }
    
//    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
//        MBProgressHUD.hide(for: self.view, animated: true)
//    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
